<template>
  <div class="allsearch">
    <section class="search-content">
      <el-row :gutter="4" type="flex" justify="start">
        <el-col :span="24">
          <el-select v-model="option" style="width:120px;" @change="handleFilter">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-input v-model="searchUsername" placeholder="搜索用户名/姓名" style="width:220px;" @keyup.enter.native="handleFilter"/>
          <el-button type="primary" @click="handleFilter">搜索</el-button>
          <el-button size="medium" type="info" @click="clearParams">清空</el-button>
        </el-col>
      </el-row>
    </section>
    <subtable
      :list-loading="listLoading"
      :table-label="zeroLabel"
      :table-data="zeroData.slice((currentpage-1)*pagesize,currentpage*pagesize)"
    >

      <el-table-column slot="first" label="用户名" min-width="100" align="center">
        <template slot-scope="scope">{{ scope.row.userName }}</template>
      </el-table-column>
      <el-table-column slot="second" label="姓名" min-width="100" align="center">
        <template slot-scope="scope">{{ scope.row.secondName }}</template>
      </el-table-column>
      <el-table-column slot="third" :label="`当前${ruleForm.name ? ruleForm.name : ''}`" min-width="100" align="center">
        <template slot-scope="scope">{{ scope.row.balance }}</template>
      </el-table-column>

      <el-table-column slot="button" :min-width="100" label="操作" prop="manage" align="center">
        <template slot-scope="scope">
          <el-dropdown
            split-button
            type="primary"
            @click="detail(scope)"
            @command="handleCommand($event,scope)"
          >明细
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="1">发放</el-dropdown-item>
              <el-dropdown-item command="2">扣减</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </subtable>
    <pagination
      :total="total"
      :current-page="currentpage"
      :page-size="pagesize"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />
    <!-- 明细 -->
    <el-dialog :visible.sync="detailDialog" :title="coinDetail">
      <el-table :data="gridData" border>
        <el-table-column property="behavior" label="行为记录" min-width="15" align="center"/>
        <el-table-column :label="`${ruleForm.name}记录`" property="coin" min-width="15" align="center"/>
        <el-table-column property="createTimeStr" label="时间" min-width="20" align="center"/>
      </el-table>
    </el-dialog>
    <!-- 金币发放与扣减 -->
    <el-dialog :visible.sync="coinDialog" :title="coinBehavior ? `${ruleForm.name}发放` : `${ruleForm.name}扣减`" width="400px">
      <el-form ref="createInfo" :model="form" label-width="80px" >
        <el-form-item label="用户名:">{{ form.userName }}</el-form-item>
        <el-form-item label="当前余额:">{{ form.balance }}</el-form-item>
        <el-form-item :label="`${ruleForm.name}值:`">
          <el-input v-if="coinBehavior" v-model="form.inflow" style="width:200px;" placeholder="发放"/>
          <el-input v-if="!coinBehavior" v-model="form.outflow" style="width:200px;" placeholder="扣减"/>
          <br><span v-if="message" style="color: red">&nbsp;&nbsp;{{ message }}</span>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.memo" style="width:200px;"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="coinDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveInfo">确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Subtable from '@/components/Eltable'
import Pagination from '@/components/Pagination' // 分页组件
import { getRewardPointAccountList, getUserDeatil, updatePointAccount } from '@/api/operate/rewardPoint' // 数据接口
import { getIntegralLogList } from '@/api/operate/integralLog' // 数据接口
import { getIntegral } from '@/api/operate/integral' // 数据接口
import { getTenantId } from '@/utils/auth'
export default {
  components: {
    Subtable,
    Pagination
  },
  data() {
    return {
      listLoading: false,
      searchUsername: '',
      coinDialog: false,
      detailDialog: false,
      gridData: [],
      coinBehavior: '2',
      coinDetail: '',
      total: 0,
      currentpage: 1,
      pagesize: 10,
      option: '用户名',
      options: [
        {
          label: '用户名',
          value: '用户名'
        },
        {
          label: '姓名',
          value: '姓名'
        }
      ],
      zeroLabel: [
        {
          label: '累计消耗', width: '', prop: 'outflowAmount'
        }, {
          label: '手机号码', width: '', prop: 'phone'
        }, {
          label: '邮箱', width: '', prop: 'email'
        }
      ],
      zeroData: [],
      listFilter: [],
      ruleForm: {},
      form: {
        userName: '',
        balance: '',
        inflow: '',
        outflow: '',
        memo: ''
      },
      message: ''
    }
  },
  mounted() {
    this.getData()
    this.getRule()
  },
  methods: {
    handleSizeChange(val) {
      this.currentpage = 1
      this.pagesize = val.value
      if (this.pagesize >= 20) {
        scrollTo(50, 800)
      }
    },
    handleCurrentChange(val) {
      this.currentpage = val.value
      if (this.pagesize >= 20) {
        scrollTo(50, 800)
      }
    },
    detail(scope) {
      this.detailDialog = true
      this.coinDetail = `${scope.row.userName}的金币明细`
      getIntegralLogList(scope.tenantId).then(res => {
        res.data.items.map(item => {
          item.coin = (item.behavior === 'deduction' ? '-' : '+') + ' ' + (item.amont ? item.amont : 0)
          if (item.behavior === 'grant') item.behavior = '发放'
          if (item.behavior === 'deduction') item.behavior = '扣减'
          if (item.createTime) item.createTimeStr = new Date((item.createTime)).toLocaleString().replace(/[\u4e00-\u9fa5]/g, '')
        })
        this.gridData = res.data.items
      })
    },
    handleCommand(command, scope) {
      if (command === '1') {
        this.coinBehavior = 'grant'
      } else if (command === '2') {
        this.coinBehavior = 'deduction'
      }
      this.coinDialog = true
      this.form = scope.row
    },
    saveInfo() {
      if (!this.form.outflow && !this.form.inflow) {
        this.message = `请输入${this.ruleForm.name}值`
        return
      } else {
        this.message = ''
      }

      if (this.coinBehavior === 'grant') {
        this.form.balance += Number(this.form.inflow)
        this.form.inflowAmount += Number(this.form.inflow)
      } else {
        this.form.balance -= Number(this.form.outflow)
        this.form.outflowAmount += Number(this.form.outflow)
      }

      updatePointAccount(this.form).then(res => {
        this.$notify({
          title: '成功',
          message: '修改成功！',
          type: 'success',
          duration: 2000
        })
        this.getData()
      })
      this.coinDialog = false
      this.form = {}
    },
    handleFilter() {
      this.zeroData = this.listFilter.filter(item => {
        if (this.option === '用户名' && item.userName.toLocaleLowerCase().indexOf(this.searchUsername.toLocaleLowerCase()) === -1) return false
        if (this.option === '姓名' && item.secondName.toLocaleLowerCase().indexOf(this.searchUsername.toLocaleLowerCase()) === -1) return false
        return true
      })
      this.total = this.zeroData.length
    },
    clearParams() {
      this.option = ''
      this.searchUsername = ''
      this.getData()
    },
    getData() {
      this.listLoading = true
      getRewardPointAccountList().then(response => {
        this.zeroData = response.data.items.filter(item => {
          if (item.tenantId !== getTenantId()) return false
          return true
        })
        this.zeroData.map(item => {
          getUserDeatil(item.userId).then(userDetail => {
            item.userName = userDetail.data.item.nickName
            item.secondName = userDetail.data.item.name
            item.phone = userDetail.data.item.verifiedMobile
            item.email = userDetail.data.item.email
            if (!item.balance) item.balance = 0
            if (!item.inflowAmount) item.inflowAmount = 0
            if (!item.outflowAmount) item.outflowAmount = 0
          })
        })
        setTimeout(() => {
          this.total = this.zeroData.length
          this.listFilter = this.zeroData
          this.listLoading = false
        }, 100)
      })
    },
    getRule() {
      getIntegral(getTenantId()).then(response => {
        if (response.data.item) {
          this.ruleForm = response.data.item
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.allsearch {
  margin-top: 0px;
  padding: 0;
  .search-content {
    width: 100%;
  }
}
</style>
